package com.example.stukotlin.coroutines

import kotlinx.coroutines.*

/**
 * 协程
 */
fun main() {
    //常规用法 关联至Job对象
    val job = Job()
    val scope = CoroutineScope(job)
    scope.launch {
        //
    }
    job.cancel()
    //async函数 获取协程执行结果
    runBlocking {
        val result = async {
            8 + 1
        }.await()
        println(result)
    }

    //async 函数串行执行
    runBlocking {
        val startTime = System.currentTimeMillis()
        val result1 = async {
            delay(1000)
            5 + 5
        }.await()

        val result2 = async {
            delay(1000)
            8 + 1
        }.await()
        println(result1 + result2)
        val endTiem = System.currentTimeMillis()
        println("cost== ${endTiem - startTime} m")
    }

    //async函数并行执行
    runBlocking {
        val startTime = System.currentTimeMillis()
        val deferred1 = async {
            delay(1000)
            5 + 4
        }

        val deferred2 = async {
            delay(1000)
            8 + 8
        }

        println("result is ${deferred1.await() + deferred2.await()}.")
        val endTime = System.currentTimeMillis()
        println("cost ${endTime-startTime} milliseconds.")
    }
}